package com.asmember;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.net.util.SubnetUtils;

/**
 * @author Grzegorz Matyszczak<BR>
 *
 */
public class CounterTool {
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ArrayList<String> input = readInput();
		StringBuilder output = new StringBuilder();
		for(String asn : input) {
			String json = RIPERequestHelper.makeRequest(asn);         
			if(json != null) {

				//parsing json to get list of IP ranges
				List<String> subnets = Parser.parseJSON(json);

				//creating all IPs set
				Set<String> allIPs = createIPsList(subnets);

				output.append(allIPs.size()+"\n");
			}
		}
		writeOutput(output.toString());

	}

	/**
	 * @param output 
	 * 
	 */
	private static void writeOutput(String output) {
		try {
			BufferedWriter br = new BufferedWriter(new FileWriter("output"));

			br.write(output);		
			
			br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		}
	}

	/**
	 * @return
	 */
	private static ArrayList<String> readInput() {
		ArrayList<String> result = new ArrayList<String>();
		try {
			BufferedReader br = new BufferedReader(new FileReader("input"));

			String line;
			
			while ((line = br.readLine()) != null) {
				result.add(line);
			}
			br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		}
		return result;
	}

	/**
	 * @param subnets
	 * @return List of all IPs in given subnets, without repeating IPs.
	 */
	private static Set<String> createIPsList(List<String> subnets) {
		Set<String> allIps = new HashSet<String>();
		for(String subnet : subnets) {
			SubnetUtils utils = new SubnetUtils(subnet);
			String[] allIpsInSubnet = utils.getInfo().getAllAddresses();
			for(String ip : allIpsInSubnet)
				allIps.add(ip);
		}
		return allIps;
	}
}